<!-- 检查检验单 -->
<template>
	<el-container>
		<el-header>
			<NavMenu activeIndex="5" />
		</el-header>
		<el-container>
			<el-main>
				<el-affix target=".el-main" :offset="60">
					<el-button text :icon="EditPen" :disabled="!isPreviewingTemplate"
						@click="createApplication">开申请</el-button>
					<el-button text :icon="UploadFilled" :disabled="!isEditingApplication"
						@click="onSave">保存</el-button>
					<el-button text :icon="Printer" :disabled="!isEditingApplication" @click="onPrint">打印</el-button>
					<el-button text :icon="Printer" :disabled="checkupApplicationTableData.length == 0"
						@click="onPrintAll">全部打印</el-button>
					<el-button text :icon="DeleteFilled" :disabled="!isEditingApplication"
						@click="deleteApplication">删除</el-button>
				</el-affix>
				<div v-if="applicationTemplateID==2" :class="['paper', {preview: isPreviewingTemplate}]">
					<div class="paper-header">第二测试医院 放射科项目</div>
					<div class="frame" style="aspect-ratio: 1 / 1;">
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">姓名：</div>
							<div class="form-value" style="flex-basis: 15%;">
								<input v-model="fskxmFormData.name" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">性别：</div>
							<div class="form-select" style="flex-basis: 8%;">
								<select v-model="fskxmFormData.sex" placeholder="" disabled>
									<option value="男">男</option>
									<option value="女">女</option>
									<option value=""></option>
								</select>
							</div>
							<div class="form-label" style="flex-basis: 10%;">年龄：</div>
							<div class="form-value" style="flex-basis: 9%;">
								<input v-model="fskxmFormData.age" disabled />
							</div>
							<div class="form-label" style="flex-basis: 11%;">职业：</div>
							<div class="form-value" style="flex-basis: 12%;">
								<input v-model="fskxmFormData.carrer" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">单位：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.workplace" disabled />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">地址：</div>
							<div class="form-value" style="flex-basis: 31%;">
								<input v-model="fskxmFormData.address" disabled />
							</div>
							<div class="form-label" style="flex-basis: 10%;">住院门诊号：</div>
							<div class="form-value" style="flex-basis: 20%;">
								<input v-model="fskxmFormData.hospitalNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 12%;">执行科室：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.department" disabled />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">科别：</div>
							<div class="form-value" style="flex-basis: 15%;">
								<input v-model="fskxmFormData.departmentType" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">床号：</div>
							<div class="form-value" style="flex-basis: 8%;">
								<input v-model="fskxmFormData.bedNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 10%;">检查号：</div>
							<div class="form-value" style="flex-basis: 9%;">
								<input v-model="fskxmFormData.checkupNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 11%;">预约检查期：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.dueDate" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">病情摘要：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.digest" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">临床诊断：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.diagnosis" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">检查部位：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.checkPart" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">注意事项：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.note" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">临床诊断：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="fskxmFormData.diagnosis" />
							</div>
						</div>
						<div class="form-row" />
						<div class="form-row">
							<checkbox-group class="form-multicheck" style="border: none; flex: 1;">
								<label class="flex-right" style="flex-basis: 3%;">
									<checkbox :checked="fskxmFormData.option_210102004_20" />
								</label>
								<div style="flex-basis: 18%;">11×14吋（·210102004·20）</div>
								<input :value="fskxmFormData.number_210102004_20"
									style="flex-basis: 10%; border: var(--el-border);" />
								<div style="flex-grow: 1; flex-shrink: 1;" />
							</checkbox-group>
						</div>
						<div class="form-row">
							<checkbox-group class="form-multicheck" style="border: none; flex: 1;">
								<label class="flex-right" style="flex-basis: 3%;">
									<checkbox :checked="fskxmFormData.option_210102003_18" />
								</label>
								<div style="flex-basis: 18%;">10×12吋（·210102003·18）</div>
								<input :value="fskxmFormData.number_210102003_18"
									style="flex-basis: 10%; border: var(--el-border);" />
								<div style="flex-grow: 1; flex-shrink: 1;" />
							</checkbox-group>
						</div>
					</div>
				</div>
				<div v-else :class="['paper', {preview: isPreviewingTemplate}]">
					<div class="paper-header">第二测试医院 检验室项目</div>
					<div class="frame" style="aspect-ratio: 1 / 1;">
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">姓名：</div>
							<div class="form-value" style="flex-basis: 15%;">
								<input v-model="jysxmFormData.name" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">性别：</div>
							<div class="form-select" style="flex-basis: 8%;">
								<select v-model="jysxmFormData.sex" placeholder="" disabled>
									<option value="男">男</option>
									<option value="女">女</option>
									<option value=""></option>
								</select>
							</div>
							<div class="form-label" style="flex-basis: 10%;">年龄：</div>
							<div class="form-value" style="flex-basis: 9%;">
								<input v-model="jysxmFormData.age" disabled />
							</div>
							<div class="form-label" style="flex-basis: 11%;">职业：</div>
							<div class="form-value" style="flex-basis: 12%;">
								<input v-model="jysxmFormData.carrer" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">单位：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.workplace" disabled />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">地址：</div>
							<div class="form-value" style="flex-basis: 31%;">
								<input v-model="jysxmFormData.address" disabled />
							</div>
							<div class="form-label" style="flex-basis: 10%;">住院门诊号：</div>
							<div class="form-value" style="flex-basis: 20%;">
								<input v-model="jysxmFormData.hospitalNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 12%;">执行科室：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.department" disabled />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">科别：</div>
							<div class="form-value" style="flex-basis: 15%;">
								<input v-model="jysxmFormData.departmentType" disabled />
							</div>
							<div class="form-label" style="flex-basis: 8%;">床号：</div>
							<div class="form-value" style="flex-basis: 8%;">
								<input v-model="jysxmFormData.bedNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 10%;">检查号：</div>
							<div class="form-value" style="flex-basis: 9%;">
								<input v-model="jysxmFormData.checkupNo" disabled />
							</div>
							<div class="form-label" style="flex-basis: 11%;">预约检查期：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.dueDate" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">病情摘要：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.digest" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">临床诊断：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.diagnosis" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">检查部位：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.checkPart" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">注意事项：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.note" />
							</div>
						</div>
						<div class="form-row">
							<div class="form-label" style="flex-basis: 8%;">临床诊断：</div>
							<div class="form-value" style="flex-grow: 1; flex-shrink: 1;">
								<input v-model="jysxmFormData.diagnosis" />
							</div>
						</div>
					</div>
				</div>
			</el-main>
			<el-aside style="border-left: var(--el-border);">
				<Card title="常用短语">
					<el-row>
						<el-col :span="1" />
						<el-col :span="4" class="flex-center"><el-text>检索：</el-text></el-col>
						<el-col :span="18">
							<el-autocomplete v-model="commonPhraseSearchWord"
								:fetch-suggestions="onCommonPhraseFetchSuggestions" clearable />
						</el-col>
						<el-col :span="1" />
					</el-row>
					<div style="height: 200px; margin: 10px;">
						<el-table ref="commonPhraseTableRef" :data="commonPhraseTableData" :max-height="200">
							<el-table-column prop="name" label="名称" show-overflow-tooltip />
							<el-table-column prop="content" label="内容" show-overflow-tooltip />
						</el-table>
					</div>
				</Card>
				<Card title="检查检验单据列表">
					<div style="margin: 10px;">
						<el-table ref="checkupApplicationTableRef" :data="checkupApplicationTableData"
							highlight-current-row @current-change="onCheckupApplicationTableCurrentChange">
							<el-table-column prop="name" label="名称" show-overflow-tooltip />
							<el-table-column prop="status" label="状态" show-overflow-tooltip />
						</el-table>
					</div>
				</Card>
				<Card title="检查检验模板">
					<el-row>
						<el-col :span="1" />
						<el-col :span="6" class="flex-left"><el-text>专业组：</el-text></el-col>
						<el-col :span="16" style="padding: 5px 10px 5px 0px;">
							<el-select v-model="applicationTemplateSelectGroup" placeholder="">
								<el-option value="全部">全部</el-option>
								<el-option value=""></el-option>
							</el-select>
						</el-col>
						<el-col :span="1" />
					</el-row>
					<el-row>
						<el-col :span="1" />
						<el-col :span="6" class="flex-left"><el-text>检索：</el-text></el-col>
						<el-col :span="16">
							<el-autocomplete v-model="applicationTemplateSearchWord"
								:fetch-suggestions="onApplicationTemplateFetchSuggestions" clearable />
						</el-col>
						<el-col :span="1" />
					</el-row>
					<div style="height: 200px; margin: 10px;">
						<el-table ref="applicationTemplateTableRef" :data="applicationTemplateTableData"
							:max-height="200" highlight-current-row
							@current-change="onApplicationTemplateTableCurrentChange">
							<el-table-column prop="name" label="模板名称" show-overflow-tooltip />
							<el-table-column prop="department" label="执行科室" show-overflow-tooltip />
							<el-table-column prop="type" label="类型" show-overflow-tooltip />
						</el-table>
					</div>
				</Card>
			</el-aside>
		</el-container>
	</el-container>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import axiosInstance from '@/Config/axiosConfig'
	import globalStore from '@/store/GlobalStore';
	import Emessage from '@/Utils/Message';
	import { ElNotification } from 'element-plus';
	import { EditPen, UploadFilled, Printer, DeleteFilled, Plus, Minus } from '@element-plus/icons-vue';
	import type { TableInstance } from 'element-plus'
	import '@/pages/doctor/styles/common.scss';
	import '@/pages/doctor/styles/form.scss';
	import NavMenu from '@/pages/doctor/components/NavMenu';
	import Card from '@/pages/doctor/components/Card';

	const docID = uni.getStorageSync('id');
	const doctorCurrentPatient = uni.getStorageSync('doctorCurrentPatient');
	const regID = doctorCurrentPatient.regID;
	const patientID = doctorCurrentPatient.patientID;

	// 检查检验单
	const applicationTemplateID = ref();
	const checkupApplicationID = ref();
	const isPreviewingTemplate = ref(false);
	const isEditingApplication = ref(false);
	let digID = null;

	const onSave = () => {
		Emessage("TODO: 保存检查检验单", "error");
	};

	const onPrint = () => {
		Emessage("TODO: 打印检查检验单", "error");
	};

	const onPrintAll = () => {
		Emessage("TODO: 打印全部检查检验单", "error");
	};

	// 放射科项目
	const fskxmFormData = ref({
		name: '张三',
		sex: '男',
		age: '50岁',
		carrer: '个体',
		workplace: '',
		address: '000',
		hospitalNo: '20150121000001',
		department: '放射科',
		departmentType: '内一科',
		bedNo: '',
		checkupNo: '',
		dueDate: '',
		digest: '',
		diagnosis: '',
		checkPart: '头颅、颈部',
		note: '',
		option_210102004_20: false,
		number_210102004_20: 1,
		option_210102003_18: false,
		number_210102003_18: 1,
	});

	// 检验室项目
	const jysxmFormData = ref({
		name: '张三',
		sex: '男',
		age: '50岁',
		carrer: '个体',
		workplace: '',
		address: '000',
		hospitalNo: '20150121000001',
		department: '检验室',
		departmentType: '内一科',
		bedNo: '',
		checkupNo: '',
		dueDate: '',
		digest: '',
		diagnosis: '',
		checkPart: '血常规',
		note: '',
	});

	// 常用短语
	const commonPhraseSearchWord = ref('');
	const commonPhraseTableRef = ref<TableInstance>();
	const commonPhraseTableData = ref([
		{ name: 'CT检查', content: '头颅、颈部' },
	]);

	const onCommonPhraseFetchSuggestions = (queryString : string, cb : any) => {
		const results = [];
		cb(results);
	};

	// 检查检验单据列表
	const checkupApplicationTableRef = ref<TableInstance>();
	const checkupApplicationTableData = ref([]);

	const getCheckupApplicationTableData = async () => {
		try {
			const response = await axiosInstance.get('/doc/getPatientDetailById?patientId=' + patientID);
			if (response.status == 200) {
				const p = response.data;
				// name.value = p.name;
				// sex.value = integer2sex(p.sex);
				// birthday.value = formatDate(new Date(p.birthday));
				if (!digID) {
					const response2 = await axiosInstance.get('/doc/getRecordByRegId?regId=' + regID);
					if (response2.status == 200) {
						const d = response2.data;
						if (d) {
							digID = d.id;
						} else {
							ElNotification({ title: '警告', message: '请先完善病历，然后再编写检查检验单。', type: 'warning', duration: 3000 });
						}
					} else {
						ElNotification({ title: response2.status, message: response2.statusText, type: 'error', duration: 3000 });
					}
				}
				if (digID) {
					const response3 = await axiosInstance.get('/doc/getDiagReportsByRecordId?recordId=' + digID);
					if (response3.status == 200) {
						const checks = response3.data;
						if (checks) {
							checkupApplicationTableData.value = checks.map(x => {
								return {
									id: x.id,
									name: {1:'心电图', 2:'X光片', 3:'身高体重测量'}[x.id],
									templateID: x.diagItemId,
									status: x.status == 'Paid' ? '已缴费' : '未缴费',
									diagnosis: x.diagnosis,
								};
							});
						}
					} else {
						ElNotification({ title: response3.status, message: response3.statusText, type: 'error', duration: 3000 });
					}
				}
			} else {
				ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		}
	}

	const onCheckupApplicationTableCurrentChange = (currentRow, oldCurrentRow) => {
		if (currentRow) {
			applicationTemplateID.value = currentRow.templateID;
			checkupApplicationID.value = currentRow.id;
			isEditingApplication.value = true;
			applicationTemplateTableRef.value.setCurrentRow(null);
		} else {
			isEditingApplication.value = false;
		}
	}

	const deleteApplication = () => {
		let index = -1;
		for (let i = 0; i < checkupApplicationTableData.value.length; i++) {
			if (checkupApplicationTableData.value[i].id === checkupApplicationID.value) {
				index = i;
				break;
			}
		}
		if (index !== -1) {
			checkupApplicationTableData.value.splice(index, 1);
			applicationTemplateID.value = null;
			checkupApplicationTableRef.value.setCurrentRow(null);
			// TODO: 删除检查检验单
		}
	}

	getCheckupApplicationTableData();

	// 检查检验模板
	const applicationTemplateSelectGroup = ref('全部');
	const applicationTemplateSearchWord = ref('');
	const applicationTemplateTableRef = ref<TableInstance>();
	const applicationTemplateTableData = ref([
		{ id: 1, name: '心电图', department: '检验室', type: '检验单' },
		{ id: 2, name: 'X光片', department: '放射科', type: '检查单' },
		{ id: 3, name: '身高体重测量', department: '检验室', type: '检验单' },
	]);

	const createApplication = async () => {
		try {
			if (!digID) {
				const response2 = await axiosInstance.get('/doc/getRecordByRegId?regId=' + regID);
				if (response2.status == 200) {
					const d = response2.data;
					if (d) {
						digID = d.id;
					} else {
						ElNotification({ title: '警告', message: '请先完善病历，然后再编写检查检验单。', type: 'warning', duration: 3000 });
					}
				} else {
					ElNotification({ title: response2.status, message: response2.statusText, type: 'error', duration: 3000 });
				}
			}
			if (digID) {
				const response3 = await axiosInstance.post('/doc/newDiag', {
					doctorId: docID,
					diagItemId: applicationTemplateID.value,
					diagRecordId: digID,
					patientId: patientID,
				});
				if (response3.status == 200) {
					// TODO: 根据检查检验单ID(而非模板ID)找到对应的行
					getCheckupApplicationTableData().then(() => {
						const index = checkupApplicationTableData.value.findIndex(r => r.templateID == applicationTemplateID.value);
						if (index != -1) {
							checkupApplicationTableRef.value.setCurrentRow(checkupApplicationTableData.value[index]);
						}
					});
				} else {
					ElNotification({ title: response3.status, message: response3.statusText, type: 'error', duration: 3000 });
				}
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		};
	};

	const onApplicationTemplateFetchSuggestions = (queryString : string, cb : any) => {
		const results = [];
		Emessage("TODO: 自动补全", "error");
		cb(results);
	};

	const onApplicationTemplateTableCurrentChange = (currentRow, oldCurrentRow) => {
		if (currentRow) {
			applicationTemplateID.value = currentRow.id;
			isPreviewingTemplate.value = true;
			checkupApplicationTableRef.value.setCurrentRow(null);
		} else {
			isPreviewingTemplate.value = false;
		}
	}
</script>

<style lang="scss" scoped>
	.preview {
		pointer-events: none;
		user-select: none;
		border: 2px dashed var(--el-border-color);
		box-shadow: unset;
	}

	.preview * {
		border-color: #EBEEF5;
		color: #C0C4CC;
		font-weight: normal;
	}
</style>